package com.taichuan.selfcheck.ui.fragment;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.orhanobut.logger.Logger;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.mvp.presenter.EmptyPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.ui.adapter.PowerLogAdapter;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class PowerOnOffFragment extends AppBaseFragment<EmptyInterface, EmptyPresenter> implements EmptyInterface {

    @BindView(R.id.page_up)
    Button page_up;
    @BindView(R.id.page_down)
    Button page_down;
    @BindView(R.id.power_log)
    RecyclerView power_log;

    private PowerLogAdapter powerLogAdapter = null;

    private List<String[]> PowerLogList = new ArrayList<>();

    //日志翻页索引
    private int position = 0;
    //日志行数
    private int LineNumber = 0;

    //开机日志文本文件夹路径
    String powerLogPath = "/sdcard/taichuan/log/";
    //开机日志文本文件路径
    String filePath = powerLogPath+"power-On-Off-Log.txt";
    //开机日志文本文件
    File file = new File(powerLogPath+"power-On-Off-Log.txt");

    private int curScrollDistance;//RecyclerView当前滑动的距离
    private final static int SCROLL_UP = 1;
    private final static int SCROLL_DOWN = 2;
    private final String TAG=getClass().getSimpleName();


    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        operateFragmentManagerBack();
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()){
            case KeyEvent.KEYCODE_2:
                scrollUIView(SCROLL_UP);
                break;
            case KeyEvent.KEYCODE_8:
                scrollUIView(SCROLL_DOWN);
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 根据滑动类型进行页面滑动
     */
    public void scrollUIView(int scrollType) {
        int height=power_log.computeVerticalScrollRange();
        int screenHeight=power_log.computeVerticalScrollExtent();
        Logger.t(TAG).e("真实高度:="+height+"  屏幕高度="+screenHeight+"  每次滑行距离="+(screenHeight / 2));

        //计算可滑动的最大距离
        int scrollMaxDistance = height - screenHeight;
        if (scrollType == SCROLL_UP) {
            if (curScrollDistance > 0) {
                curScrollDistance = curScrollDistance - screenHeight / 2;//每次滑动控件的1/2高度距离
               if(curScrollDistance <=0){
                    power_log.smoothScrollBy(0, - (screenHeight/2));
                    curScrollDistance = 0;
                    Logger.t(TAG).e("about_scroll滑动距离:" + curScrollDistance );
                } else{
                    power_log.smoothScrollBy(0, -curScrollDistance);
                }
                Logger.t(TAG).e("about_scroll滑动距离:" + curScrollDistance + "  滑动最大距离:" + scrollMaxDistance);
            }else {
                Logger.t(TAG).e("已到顶部，无需滑动:");
            }
        } else {
            if (curScrollDistance < scrollMaxDistance) {
                curScrollDistance = curScrollDistance + screenHeight / 2;//每次滑动控件的1/2高度距离
                power_log.smoothScrollBy(0, curScrollDistance);
                Logger.t(TAG).e("about_scroll滑动距离:" + curScrollDistance + "  滑动最大距离:" + scrollMaxDistance);
            } else {
                curScrollDistance = scrollMaxDistance;
                Logger.t(TAG).e("已到底部，无需滑动:"+curScrollDistance);
            }
        }
    }


    @Override
    protected int setContentViewId() {
        return R.layout.fragment_power_on_off;
    }

    @Override
    protected void initView(View view, Bundle bundle) {

        powerLogAdapter = new PowerLogAdapter(PowerLogList);

        power_log.setLayoutManager(new LinearLayoutManager(getContext()));
        power_log.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

        power_log.setAdapter(powerLogAdapter);
        power_log.setVisibility(View.VISIBLE);

        readText(filePath);

        page_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position += 10;
                if (position>LineNumber)
                    position = LineNumber;
                power_log.smoothScrollToPosition(position);
            }
        });

        page_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position -= 10;
                if (position<0)
                    position = 0;
                power_log.smoothScrollToPosition(position);
            }
        });
    }

    @Override
    protected EmptyPresenter createPresenter() {
        return new EmptyPresenter();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    /**
     * 倒序读取文本内容
     * @param file  文件路径
     */
    public void readText(String file){
        RandomAccessFile r = null;
        try {
            r = new RandomAccessFile(file, "r");
            long start = r.getFilePointer();
            long nextend = start + r.length() - 1;
            String result;
            r.seek(nextend);
            int c = -1;
            while (nextend >= start) {
                c = r.read();
                if (c == '\n' || c == '\r') {
                    //读取一行
                    result = r.readLine();
                    LineNumber++;
                    //将字符串转码成UTF-8格式，解决乱码问题
                    String UTFString = new String(result.getBytes("ISO-8859-1"), "UTF-8");
                    //根据空格分割字符串
                    String[] LineLog = UTFString.split(" ");
                    powerLogAdapter.addData(PowerLogList.size(),new String[]{LineLog[0]+" "+LineLog[1],LineLog[2]});
                    nextend--;
                }
                nextend--;
                if(nextend>=0) {
                    r.seek(nextend);
                    if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
                        //TODO 此句勿删,消耗文本第一行空白
                        r.readLine();
                        //将字符串转码成UTF-8格式，解决乱码问题
                        String UTFString = new String(r.readLine().getBytes("ISO-8859-1"), "UTF-8");
                        //根据空格分割字符串
                        String[] LineLog = UTFString.split(" ");
                        powerLogAdapter.addData(PowerLogList.size(),new String[]{LineLog[0]+" "+LineLog[1],LineLog[2]});
                        LineNumber++;
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (r != null)
                try {
                    r.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
